package com.hmdp.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

import static com.hmdp.utils.RedisConstants.CACHE_SHOPTYPE_KEY;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Override
    public Result queryAll() {
        //1.设置Redis的key（包括第一次）
        String key =CACHE_SHOPTYPE_KEY;
        //2.查询Redis缓存
        String shopTypeJson = stringRedisTemplate.opsForValue().get(key);
        //3.1判断Redis中是否存在数据
        if (StrUtil.isBlank(shopTypeJson)) {
            //3.2.如果不存在，访问数据库
            List<ShopType> shopTypeList = query().orderByAsc("sort").list();
            //3.3.如果数据库为空，报错
            if (shopTypeList == null) {
                return Result.fail("数据不存在");
            }
            //3.4.如果存在，写入Redis
            stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shopTypeList));
            return Result.ok(shopTypeList);
        }
        //4.若是Redis中存在直接返回
        List<ShopType> shopTypeList = JSONUtil.toList(shopTypeJson, ShopType.class);
        return Result.ok(shopTypeList);
    }
}
